-- ToME - Tales of Middle-Earth
-- Copyright (C) 2009, 2010 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program.  If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org

require "engine.class"
local Map = require "engine.Map"
require "engine.Generator"
local Random = require "engine.generator.actor.Random"

--- Very specialized generator that puts sandworms in interresting spots to dig tunnels
module(..., package.seeall, class.inherit(engine.Generator))

function _M:init(zone, map, level, spots)
	engine.Generator.init(self, zone, map, level, spots)
	self.data = level.data.generator.actor

	self.random = Random.new(zone, map, level, spots)
end

function _M:generate()
	-- Make the random generaor place normal actors
	self.random:generate()

	-- Find all of the beds
	local beds = {}
	local apply = function(tx, ty)
		local terrain = game.level.map(tx, ty, Map.TERRAIN)
		if terrain and terrain.define_as == "BED" then
			table.insert(beds, {x=tx, y=ty})
		end
	end
	game:floodFill(1, 1, function() return true end, apply)
	local nb_patients
	if type(self.data.nb_patients) == "table" then
		nb_patients = rng.range(unpack(self.data.nb_patients))
	else
		nb_patients = self.data_nb_patients or 10
	end
	-- And then fill the beds with patients!  (one per bed please)
	while nb_patients > 0 and #beds > 0 do
		local bed, id = rng.table(beds)
		local patient = game.zone:makeEntityByName(game.level, "actor", "PATIENT")
		game.zone:addEntity(game.level, patient, "actor", bed.x, bed.y)
		nb_patients = nb_patients - 1
		-- Remove the used location from the possibilities
		local check = function(tx, ty)
			local terrain = game.level.map(tx, ty, Map.TERRAIN)
			return terrain.define_as == "BED"
		end
		local apply = function(tx, ty)
			for k, v in pairs(beds) do
				if v.x == tx and v.y == ty then
					table.remove(beds, k)
					break
				end
			end
		end
		game:floodFill(bed.x, bed.y, check, apply)
	end
end